package com.xxxx.yebserver.service.impl;

import com.xxxx.yebserver.entity.Department;
import com.xxxx.yebserver.mapper.DepartmentMapper;
import com.xxxx.yebserver.service.DepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cxq
 * @since 2021-06-15
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {


    private List<Department> setDepartmentChildren(List<Department> vos, Long pid){
        return vos.stream().filter(vo->vo.getParentId() == pid)
                .map(vo->{
                    vo.setChildren(setDepartmentChildren(vos,vo.getId()));
                    return vo;
                }).collect(Collectors.toList());
    }

    /**
     * 获取所有部门列表
     * @return
     */
    @Override
    public List<Department> getTreeDepartment() {
        List<Department> list = list();
        List<Department> departments = setDepartmentChildren(list, 0L);
        return departments;
    }

    @Override
    public boolean saveDep(Department department) {
        department.setStatus(true);
        baseMapper.saveDep(department);
        if(department.getResult() == 1) return true;
        return false;
    }

    @Override
    public boolean deleteDep(Long id) {
        Department dep = new Department();
        dep.setId(id);
        baseMapper.deleteDep(dep);
        if(dep.getResult() == -2) throw new RuntimeException("该部门下还有子部门，无法删除");
        if(dep.getResult() == -1) throw new RuntimeException("该部门下有员工，无法删除");
        if(dep.getResult() == 1) return true;
        return false;
    }
}
